<template>
    <div class=''>
        <public-Dialog
                v-model:visible="visible"
                title="管控至项目"
                width="50%"
                confirm-button-title="提交"
                @on-confirm="onConfirm"
                >
            <template #default>
                <el-descriptions
                        v-if="projectInfo"
                        title="基本信息"
                        direction="vertical"
                        :column="4"
                        border
                >
                    <el-descriptions-item label="项目集">{{projectInfo.firstMainProjectName}}</el-descriptions-item>
                    <el-descriptions-item label="项目子集">{{projectInfo.mainProjectName}}</el-descriptions-item>
                    <el-descriptions-item label="科目" :span="2">{{projectInfo.subjectName || '无'}}</el-descriptions-item>
                    <el-descriptions-item label="资金计划金额">{{projectInfo.budgetAmount}}</el-descriptions-item>
                    <el-descriptions-item label="日期">
                        {{projectInfo.year}}年|{{projectInfo.quarter}}季度|{{projectInfo.monthly}}月
                    </el-descriptions-item>
                </el-descriptions>
                <div class="m-t20 m-b10">
                    <el-button class="button_edit" @click="handleAdd">新增</el-button>
                    <el-button class="button_edit" @click="copyHandle">复制</el-button>
                    <el-button class="button_edit" @click="reduceHandle">删除</el-button>
                </div>
                <el-form label-width="0px" ref="tableFormRef" :model="form">
                    <public-table
                            ref="publicTableRef"
                            index
                            :is-paging="false"
                            border
                            radio
                            height="300"
                            :page="page"
                            :tableData="form.list"
                            :header-cell-style="{background: '#F5F7FA'}"
                            :cell-style="{background: 'revert'}"
                            :tableOption.sync="tableOption"
                            @handleSelectionChange="handleSelectionChange"
                    >
                        <template #projectId="scope">
                            <el-form-item :prop="'list.' + scope.$index + '.projectId'" :rules="rules.projectId">
                                <el-select v-model="scope.row.projectId" placeholder="请选择" style="width: 100%;" @change="projectChange($event, scope.$index)">
                                    <el-option
                                            v-for="item in projectList"
                                            :key="item.projectId"
                                            :label="item.projectName"
                                            :value="item.projectId">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </template>
                        <template #contractId="scope">
                            <el-form-item :prop="'list.' + scope.$index + '.contractId'" :rules="rules.contractId">
                                <el-select v-model="scope.row.contractId" placeholder="请选择" style="width: 100%;">
                                    <el-option
                                            v-for="item in form.list[scope.$index].contractList"
                                            :key="item.contractId"
                                            :label="item.contractName" :value="item.contractId">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </template>
                        <template #budgetAmount="scope">
                            <el-form-item :prop="'list.' + scope.$index + '.budgetAmount'" :rules="rules.budgetAmount">
                                <el-input v-model="scope.row.budgetAmount"></el-input>
                            </el-form-item>
                        </template>
                        <template #remarks="scope">
                            <el-form-item :prop="'list.' + scope.$index + '.remarks'" :rules="rules.remarks">
                                <el-input v-model="scope.row.remarks"></el-input>
                            </el-form-item>
                        </template>
                    </public-table>
                </el-form>
            </template>
        </public-Dialog>
    </div>
</template>

<script setup>
import {onMounted, reactive, ref} from "vue";
import PublicDialog from "@/components/PublicDialog.vue";
import {budgetManagement, fundManagementApi, otherApi} from "@/api/businessFinance";
import {ElDescriptions, ElDescriptionsItem, ElSelect, ElOption, ElForm, ElFormItem, ElMessage} from "element-plus";
import PublicTable from "@/components/PublicTable.vue";

let visible = ref(false);

const form = reactive({
    budgetPlanId:"",
    list:[]
});

const rules = reactive({
    projectId: [
        { required: true, message: "项目不能为空!", trigger: "change" },
    ],
    // contractId: [{ required: true, message: "合同不能为空!", trigger: "change" }],
    budgetAmount: [
        { required: true, message: "资金预算金额不能为空!", trigger: "blur" },
    ],
    remarks: [
        { required: true, message: "备注不能为空!", trigger: "blur" },
    ],
});


const projectInfo = ref(null);

/**
 * 打开弹窗
 */
const openPopup = (budgetPlanId) => {
    form.budgetPlanId = budgetPlanId;
    form.list = [];
    fundManagementApi.getDepartmentBudgetPlanDetailContract({budgetPlanId:budgetPlanId}).then(res => {
        if(res.code === "200"){
            projectInfo.value = res.data;
            form.list = res.data.list || [];
            visible.value = true;
        }
    });
}

/**
 * 关闭弹窗
 */
const closePopup = () => {
  visible.value = false;
}

const getUuid = () => {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = (Math.random() * 16) | 0,
            v = c == 'x' ? r : (r & 0x3) | 0x8;
        return v.toString(16);
    });
}

/**
 * 选中行
 */
const list = ref([]);
const handleSelectionChange = (e) => {
    list.value = e;
}

/**
 * 新增
 */
const handleAdd = () => {
  form.list.push({
      uuid: getUuid(),
      projectId:"",
      contractId:"",
      budgetAmount:"",
      remarks:""
  });
}

const reduceHandle = () => {
    if (list.value.length === 0) {
        ElMessage.warning("请选择需要操作的行!");
        return;
    }
    list.value.forEach((item) => {
        form.list.forEach((val, index) => {
            if (item.uuid === val.uuid) {
                form.list.splice(index, 1);
            }
        });
    });
};

/**
 * 复制
 */
const copyHandle = () => {
    if (list.value.length === 0) {
        ElMessage.warning("请选择需要操作的行!");
        return;
    }
    let newList = JSON.parse(JSON.stringify(list.value));
    for (let item of newList){
        item.uuid = getUuid();
    }
    form.list.push(...newList);
}

const page = reactive({
    total: 0,
    current: 1,
    size: 10
});

const tableData = ref([]);

const tableOption = ref([
    { label: "项目名称", prop: "projectId", minWidth: 80,slot:true },
    { label: "合同", prop: "contractId", minWidth: 80,slot:true },
    { label: "资金计划金额 ", prop: "budgetAmount", minWidth: 120,slot:true },
    { label: "备注", prop: "remarks", minWidth: 80,slot:true },
]);

const projectList = ref([]);

/**
 * 获取项目列表
 */
const getProjectList = () => {
    budgetManagement.getProjectList().then(res => {
        if(res.code === "200"){
            projectList.value = res.data;
        }
    });
}

/**
 * 查询项目下的合同
 *
 */
const getListByProjectId = (projectId, i) => {
    otherApi.getContractList(projectId).then((res) => {
        form.list[i].contractList = res.data;
    });
};

/**
 * 获取合同列表
 */
const projectChange = (e,i) => {
    if (e) {
        getListByProjectId(e, i);
        form.list[i].contractList = [];
        form.list[i].contractId = "";
    } else {
        form.list[i].contractList = [];
        form.list[i].contractId = "";
    }
}

/**
 * 确认
 */
const emits = defineEmits(["on-success"]);
const tableFormRef = ref(null);
const onConfirm = async () => {
    if(!form.list.length){return ElMessage.warning('请添加数据!')}
    await tableFormRef.value.validate();
    fundManagementApi.addBudgetPlanDetailContract(form).then(res => {
        if(res.code === "200"){
            ElMessage.success("操作成功!");
            closePopup();
            emits("on-success");
        }
    });
}

onMounted(()=>{
    getProjectList();
});

defineExpose({ openPopup,closePopup });
</script>

<style lang="scss" scoped>
.content {
  display: flex;
  justify-content: space-around;
  align-items: center;
}
</style>
